/*
Input: tmp/voter_id_panel.dta [address - precinct assignments + geocodes of addresses and polling locations]
	
Output: voter and polling location files with geocodes

Main task: export .txt with geo-coordinates for maps

*/

* PULL: data containing address - precinct assignments + geocodes of addresses and polling locations 
use "$tmp/voter_id_panel.dta", clear

***Figure 2
preserve
*voter: addresses and assigned polling places
	keep if wahl_id==6
	bys voter_id_str: assert _N==1
	keep voter_id_str lat_vote lon_vote lat_wl lon_wl
	export delim "$rawdata/shp/shapes_fig2/voter18.txt", replace
restore

preserve
*polling places: addresses
	keep if wahl_id==6
	keep wl_id lat_wl lon_wl
	bys wl_id: keep if _n==1
	export delim "$rawdata/shp/shapes_fig2/wl18.txt", replace
restore


***Figure 3a
preserve
*voter: 2017
	tempfile voter17_806
	keep if wahl_id==5 & sb==806
	bys voter_id_str: assert _N==1
	keep voter_id_str lat_vote lon_vote lat_wl lon_wl
	export delim "$rawdata/shp/shapes_fig3a/voter17_806.txt", replace
	keep voter_id_str
	save `voter17_806'
restore

preserve
*voter: 2014
	keep if wahl_id==4
	merge 1:1 voter_id_str using `voter17_806', assert(1 3) keep(3) nogen
	bys voter_id_str: assert _N==1
	keep voter_id_str lat_vote lon_vote lat_wl lon_wl
	export delim "$rawdata/shp/shapes_fig3a/voter14_806.txt", replace
restore


preserve
*polling places: 2014
	keep if wahl_id==4 & (wl_id=="theresienhoehe15" | wl_id=="ridlerstrasse26")
	keep wl_id lat_wl lon_wl
	bys wl_id: keep if _n==1
	export delim "$rawdata/shp/shapes_fig3a/wl14_806.txt", replace
restore

preserve
*polling places: 2017
	keep if wahl_id==5 & wl_id=="ridlerstrasse26"
	keep wl_id lat_wl lon_wl
	bys wl_id: keep if _n==1
	export delim "$rawdata/shp/shapes_fig3a/wl17_806.txt", replace
restore


***Figure 3b
preserve
*voter: 2017
	tempfile voter17_612
	keep if wahl_id==5 & sb==612
	bys voter_id_str: assert _N==1
	keep voter_id_str lat_vote lon_vote lat_wl lon_wl
	export delim "$rawdata/shp/shapes_fig3b/voter17_612.txt", replace
	keep voter_id_str
	save `voter17_612'
restore

preserve
*voter: 2014
	keep if wahl_id==4
	merge 1:1 voter_id_str using `voter17_612', assert(1 3) keep(3) nogen
	tab wl_id
	bys voter_id_str: assert _N==1
	keep voter_id_str lat_vote lon_vote lat_wl lon_wl
	export delim "$rawdata/shp/shapes_fig3b/voter14_612.txt", replace
restore



preserve
*polling places: 2014
	keep if wahl_id==4 & (wl_id=="gotzingerplatz1" | wl_id=="wackersbergerstrasse59")
	keep wl_id lat_wl lon_wl
	bys wl_id: keep if _n==1
	export delim "$rawdata/shp/shapes_fig3b/wl14_612.txt", replace
restore

preserve
*polling places: 2017
	keep if wahl_id==5 & (wl_id=="gotzingerplatz1" | wl_id=="wackersbergerstrasse59")
	keep wl_id lat_wl lon_wl
	bys wl_id: keep if _n==1
	export delim "$rawdata/shp/shapes_fig3b/wl17_612.txt", replace
restore
